package com.bcbim.common.compress;

import com.google.common.primitives.Bytes;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Author: ye
 * @Date: 2022/7/6
 * @Version: V1.0
 **/
public class Compress {

    private List<Dictionary> dictionaries;

    private List<Byte> result = new ArrayList<>();

    public Compress() {
        dictionaries = new ArrayList<>();
    }

    public byte[] compressData(byte[] data) {
        if (data == null || data.length == 0) {
            return data;
        }
        List<Byte> goal = new ArrayList<>();
        int lastIndex = 0;
        for (int i = 0; i < data.length; i++) {
            goal.add(data[i]);
            int index = findDictionary(Bytes.toArray(goal));
            if (index != -1) {
                lastIndex = index;
                continue;
            }
            result.add((byte) (lastIndex<<24));
            result.add((byte) (lastIndex<<16));
            result.add((byte) (lastIndex<<8));
            result.add((byte) lastIndex);
            result.add(data[i]);
            addDictionary(goal);
            goal = new ArrayList<>();
            lastIndex = 0;
        }
        return Bytes.toArray(result);
    }

    private void addDictionary(List<Byte> goal) {
        Dictionary dictionary = new Dictionary();
        for (Byte b : goal) {
            dictionary.addNode(b);
        }
        dictionaries.add(dictionary);
        if (dictionaries.size() > Integer.MAX_VALUE) {
            dictionaries.remove(dictionaries.size() - 1);
        }
    }

    private int findDictionary(byte[] arrByte) {
        int i = 1;
        for (Dictionary dictionary : dictionaries) {
            if (dictionary.checkEquals(arrByte)) {
                return i;
            }
            i++;
        }
        return -1;
    }

}
